var log4js = require('log4js');
var path = require('path');
var handler = require('./modules/njcore/handler');
var schedule = require('./modules/sys/schedule');
var fs = require('fs');
var package = require('./package.json');

if (!global.sysConfig) {
    process.setMaxListeners(0);
    require(path.join(process.cwd(), './config', 'config.js'));
    require('./modules/sys/protoUtil');
    log4js.configure(sysConfig.log4js);
    global.__njserverVersion = package.version;
    global.log4js = log4js;
    global.logger = log4js.getLogger();
    global.routeMap = [];
    global.interceptorBeforeMap = [];
    global.interceptorAfterMap = [];
}

module.exports = {
    listen: () => {
        var sessionManager = require('./modules/njcore/sessionManager');
        sysConfig.servers.forEach(server => {
            var http = require(server.protocol);
            if (server.key && server.cert) {
                var options = {
                    key: fs.readFileSync(server.key),
                    cert: fs.readFileSync(server.cert)
                };
                (http.createSecureServer || http.createServer)(options, function (req, res) {
                    req.originalUrl = 'https://' + (req.headers.host || req.authority) + req.url;
                    handler(req, res, sessionManager);
                }).listen(server.port);

                logger.info('Https Server runing at port: ' + server.port + ' ...');
            } else {
                http.createServer(function (req, res) {
                    req.originalUrl = 'http://' + (req.headers.host || req.authority) + req.url;
                    handler(req, res, sessionManager);
                }).listen(server.port);

                logger.info('Http Server runing at port: ' + server.port + ' ...');
            }
        });

        schedule.add('sessionManager', sysConfig.sessionClearTime, sessionManager.autoClear);
        schedule.startAll();
    },

    use: (url, dirOrInvoke) => {
        if (dirOrInvoke.before)
            interceptorBeforeMap.push({
                url: url,
                dirOrInvoke: dirOrInvoke.before
            });
        if (dirOrInvoke.after)
            interceptorAfterMap.push({
                url: url,
                dirOrInvoke: dirOrInvoke.after
            });
        else
            routeMap.push({
                url: url,
                dirOrInvoke: dirOrInvoke
            });
    },

    mysql: require('./modules/sys/mysql'),
    mssql: require('./modules/sys/mssql'),
    schedule: require('./modules/sys/schedule'),
    fileUtil: require('./modules/sys/fileUtil')
};